﻿using System;
using System.Web;
using System.Web.SessionState;
using System.Configuration;
using RN.ERP.Web.BasicService;
using Newtonsoft.Json;

namespace RN.ERP.Web.Message
{
    /// <summary>
    /// 消息推送模块
    /// 处理消息的接收，分发，管理
    /// </summary>
    public class ChatHandler : IHttpHandler, IRequiresSessionState
    {
        #region Params

        private int AppID
        {
            get
            {
                return int.Parse(ConfigurationManager.AppSettings["AppId"]);
            }
        }

        private HttpRequest Request
        {
            get
            {
                return HttpContext.Current.Request;
            }
        }

        private HttpResponse Response
        {
            get
            {
                return HttpContext.Current.Response;
            }
        }

        private BasicServiceClient bsc = new BasicServiceClient();

        private SessionUserInfo _user = null;
        private SessionUserInfo User
        {
            get
            {
                if (_user == null)
                    _user = (SessionUserInfo)HttpContext.Current.Session[SessionConstant.SESSION_USERINFO];
                return _user;
            }
        }

        private string Sender
        {
            get
            {
                return Request["Sender"];
            }
        }

        private DateTime? LastSearchTime
        {
            set
            {
                HttpContext.Current.Session["LastSearchTime"] = value;
            }
            get
            {
                var lst = HttpContext.Current.Session["LastSearchTime"];
                if (Request["IsPageLoad"] == "true" || lst == null)
                    return null;
                else
                    return (DateTime)lst;
            }
        }

        #endregion

        public void ProcessRequest(HttpContext context)
        {
            FuncRoute();
        }

        /// <summary>
        /// 函数路由
        /// </summary>
        private void FuncRoute()
        {
            string func = Request["func"] ?? "";
            try
            {
                switch (func.ToLower())
                {
                    case "send":
                        SendMsg(); break;
                    case "gethistory":
                        GetHistory();break;
                    case "getchatbrief":
                        GetChatBrief();break;
                    default:
                        ReceiveAll(); break;
                }
            }
            catch (Exception ex)
            {
                Print("{'error':'" + ex.Message + "'}");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private void SendMsg()
        {
            BasicServiceClient bsc = new BasicServiceClient();
            DateTime sendTime = DateTime.Now;
            object rst = null;
            try
            {
                T_Chat_ChatInfo chatInfo = new T_Chat_ChatInfo
                {
                    AppID = AppID,
                    Sender = User.CorpUserGuid,
                    Receiver = Request["Receiver"],
                    SendTime = sendTime,
                    MsgText = Request["MsgText"],
                    AreaCode = User.AreaCode
                };

                bsc.SendChat(chatInfo);
                rst = new { Result = "success", SendTime = sendTime };
            }
            catch (Exception ex)
            {
                rst = new { Result = "fail", SendTime = sendTime };
            }
            Print(JsonConvert.SerializeObject(rst));
        }

        private void ReceiveAll()
        {
            DateTime searchTime = DateTime.Now;
            var ChatList = bsc.GetChatInfos(User.CorpUserGuid, null, AppID, LastSearchTime, false, true, User.AreaCode);
            LastSearchTime = searchTime;
            Print(JsonConvert.SerializeObject(ChatList));
        }

        private void GetHistory()
        {
            DateTime st,et;
            DateTime? StartTime = null;
            DateTime? EndTime = null;
            
            if(DateTime.TryParse(Request["StartTime"], out st))
            {
                StartTime = st;
            }
            if (DateTime.TryParse(Request["EndTime"], out et))
            {
                EndTime = et;
            }

            var ChatList = bsc.GetChatHistory(User.CorpUserGuid, Sender, AppID, StartTime, EndTime, User.AreaCode);
            Print(JsonConvert.SerializeObject(ChatList));
        }

        /// <summary>
        /// 获取简讯
        /// </summary>
        private void GetChatBrief()
        {
            var ChatBriefList = bsc.GetChatBrief(User.CorpUserGuid, 5, AppID);
            Print(JsonConvert.SerializeObject(ChatBriefList));
        }

        private void Print(string content)
        {
            Response.ContentType = "text/plain";
            Response.Write(content);
        }
    }
}